# coding=utf-8
__author__ = 'liubin'

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

from flask import Flask
# 数据库
from flask.ext.sqlalchemy import SQLAlchemy
# 国际化
from flask.ext.babelex import Babel, gettext as _
# 登录
from flask.ext.login import LoginManager, current_user
# restful
from flask.ext.restful import Api

# 初始化Flask
app = Flask(__name__)
app.config.from_pyfile('config.py')

# SQLAlchemy 数据库
db = SQLAlchemy(app)
from models import *
# babel 国际化
babel = Babel(app)
@babel.localeselector
def get_locale():
    return 'zh'

# 登录管理
login_manager = LoginManager(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(id):
    # Return an instance of the User model
    return User.query.get(int(id))
#加载restful
api_view = Api(app)
#加载Views
from project.views import *


def init_db():
    import constants
    db.drop_all()
    db.create_all()
    # 初始化权限表
    for role in constants.roles:
        db.session.add(Role(role['code'], role['name']))
    # 初始化用户表
    for user in constants.users:
        c_user = User(user['name'], user['pwd'], user['real_name'])
        c_role = Role.query.filter_by(code=user['role']).first()
        if c_role is not None:
            c_user.roles.append(c_role)
        db.session.add(c_user)
    db.session.commit()